/* eslint-disable @typescript-eslint/no-explicit-any */
import RuntimeMessage from '@root/src/utils/RuntimeMessage';
import reloadOnUpdate from 'virtual:reload-on-update-in-background-script';
import Browser from 'webextension-polyfill';
import { getItem, setItem, generateUUID } from '../../utils/helper';

reloadOnUpdate('pages/background');

const BASEURL = 'https://admin.buerluoji.cn';
// const BASEURL = 'http://192.168.1.154:8082';
let USERID: any = '';

async function setUserId() {
  let sc: any = '';
  try {
    sc = await getItem('booleanUid');
    if (!sc) {
      const booleanUid = generateUUID();
      USERID = booleanUid;
      await setItem('booleanUid', booleanUid);
      console.log('new id', booleanUid);
    } else {
      USERID = sc;
    }
  } catch (error) {
    const booleanUid = generateUUID();
    USERID = booleanUid;
    await setItem('booleanUid', booleanUid);
  }

  return USERID;

  // 检查是否已经生成过唯一ID
  // chrome.storage.local.get(['booleanUid'], function (result) {
  //   if (result.booleanUid) {
  //     console.log('Unique ID:', result.booleanUid);
  //     USERID = result.booleanUid;
  //   } else {
  //     // 如果没有，生成并保存一个新的唯一ID
  //     const booleanUid = generateUUID(); // 使用时间戳作为简单唯一ID
  //     chrome.storage.local.set({ booleanUid: booleanUid }, function () {
  //       console.log('New Unique ID:', booleanUid);
  //       USERID = booleanUid;
  //     });
  //   }
  // });
}

async function injectContentScript(tabId: number) {
  try {
    const isInjected = await new Promise<boolean>((resolve) => {
      Browser.tabs
        .sendMessage(tabId, { type: 'init' })
        .then(() => resolve(true))
        .catch(() => resolve(false));
    });
    if (isInjected) return;

    await Browser.scripting.executeScript({
      target: { tabId },
      files: ['/src/pages/content/index.js'],
    });
  } catch (error) {
    console.error(error);
  }
}

Browser.action.onClicked.addListener((tab) => {
  if (!tab.id) return;
  injectContentScript(tab.id);
});

// DEV ONLY
// if (import.meta.env.MODE === 'development') {
Browser.tabs.onUpdated.addListener((tabId, changeInfo) => {
  if (!changeInfo.status || changeInfo.status !== 'complete') return;
  Browser.tabs.get(tabId).then((tab) => {
    if (!tab.url) return;
    injectContentScript(tabId);
  });
});
// }

RuntimeMessage.onMessage('background:screenshot-tab', (sender) => {
  if (!sender.tab?.windowId) return Promise.resolve('');
  return Browser.tabs.captureVisibleTab(sender.tab.windowId, { quality: 70 });
});

/**
 * Extension reloading is necessary because the browser automatically caches the css.
 * If you do not use the css of the content script, please delete it.
 */

// 解析和处理事件数据
function handleEvent(eventData: string) {
  console.log('eventData: ', eventData);
  // SSE 数据通常是 `data: <your data>` 格式
  const dataLines = eventData.split('\n');
  console.log('dataLines: ', dataLines);

  // 提取数组中的字符串
  const dataString = dataLines[0];

  // 去掉 `data:` 前缀
  const jsonString = dataString.slice(5);

  // 解析 JSON 字符串
  const parsedData = JSON.parse(jsonString);

  // 访问解析后的数据
  if (parsedData !== '[DONE]') {
    if (parsedData.type === 'answer' && !parsedData.created_at) {
      const parsedContent = parsedData.content;
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs: any) => {
        return chrome.tabs.sendMessage(tabs[0].id, {
          action: 'STREAMANSWER',
          data: parsedContent,
        });
      });
    }
  }
}

async function createChat(request: any, sendResponse: any) {
  try {
    const response = await fetch(`${BASEURL}/bool-admin/api/ai/session`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userId: request.data }),
    });
    const data = await response.json();
    sendResponse({ status: true, msg: data });
  } catch (error) {
    sendResponse({ status: false, msg: error.message });
    console.error('Error:', error);
  }
}

async function createMessage(request: any, sendResponse: any) {
  const body = {
    userId: USERID,
    content: request.data,
  };
  try {
    const response = await fetch(`${BASEURL}/bool-admin/api/ai/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    const data = await response.json();
    sendResponse({ status: true, msg: data });
  } catch (error) {
    sendResponse({ status: false, msg: error.message });
    console.error('Error:', error);
  }
}

async function createStreamMessage(request: any, sendResponse: any) {
  const body = {
    userId: USERID,
    content: request.data,
  };

  fetch(`${BASEURL}/bool-admin/api/ai/chat-stream`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  })
    .then(async (response: any) => {
      if (
        response.ok &&
        response.headers.get('Content-Type') === 'text/event-stream'
      ) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder(); // 用于解码流中的二进制数据
        let dataBuffer = '';

        // 处理流数据
        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read();

          if (done) {
            break; // 结束读取
          }

          dataBuffer += decoder.decode(value, { stream: true });

          // 每次接收到事件后处理
          let boundaryIndex;
          while ((boundaryIndex = dataBuffer.indexOf('\n\n')) !== -1) {
            const eventData = dataBuffer.slice(0, boundaryIndex).trim();
            dataBuffer = dataBuffer.slice(boundaryIndex + 2); // 剩余部分
            // 解析并处理事件数据
            handleEvent(eventData);
          }
        }
      } else {
        console.error('Failed to fetch event stream');
        sendResponse({
          status: false,
          msg: 'Failed to fetch event stream',
        });
      }
    })
    .catch((error) => {
      sendResponse({ status: false, msg: error.message });
      console.error('Error:', error);
    });
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  setUserId().then((result) => {
    console.log('result: ', result);
    if (request.action === 'CREATE_CHAT') {
      createChat(request, sendResponse);
    }
    if (request.action === 'CREATE_MESSAGE') {
      getItem('isStream').then((result) => {
        if (result) {
          createStreamMessage(request, sendResponse);
        } else {
          createMessage(request, sendResponse);
        }
      });
    }
    if (request.action === 'CREATE_MESSAGE_FLOAT') {
      getItem('isStream').then((result) => {
        if (result) {
          createStreamMessage(request, sendResponse);
        } else {
          createMessage(request, sendResponse);
        }
      });
    }
  });
  return true;
});

chrome.runtime.onInstalled.addListener(async () => {
  // 检查是否已经生成过唯一ID
  setUserId();

  chrome.contextMenus.create({
    id: 'openBooleanInspect',
    title: '开启Boolean Inspect',
    contexts: ['all'],
  });

  chrome.contextMenus.create({
    id: 'simulateTyping',
    title: 'Boolean-模拟输入',
    contexts: ['editable'],
  });
});

chrome.contextMenus.onClicked.addListener(function (info) {
  console.log('info: ', info);
  if (info.menuItemId === 'openBooleanInspect') {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      if (!tabs[0].id) return;
      injectContentScript(tabs[0].id);
    });
  }

  if (info.menuItemId === 'simulateTyping') {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: 'simulateTyping' });
    });
  }
});

console.log('background loaded');
